package com.icebartech.base.modules.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.icebartech.base.modules.user.dto.AppMenuInfoDTO;
import com.icebartech.base.modules.user.mapper.AppMenuMapper;
import com.icebartech.base.modules.user.model.AppMenu;
import com.icebartech.base.modules.user.service.AppMenuService;
import com.icebartech.core.modules.AbstractService;
import com.icebartech.core.modules.BaseMapper;
import com.icebartech.core.utils.ExtBeanUtils;

@Service
public class AppMenuServiceImpl extends AbstractService implements AppMenuService {
    
    private static Logger logger = LoggerFactory.getLogger(AppMenuServiceImpl.class);
    
    @Autowired
    private AppMenuMapper appMenuMapper;
    
    
    @Override
    public BaseMapper getBaseMapper() {
        return this.appMenuMapper;
    }
    
    @Override
    public List<AppMenuInfoDTO> findAppNavbarMenusByRoleKey(String roleKey) {
    	List<AppMenuInfoDTO> appMenuInfos1 = new ArrayList<>();
    	
    	List<AppMenu> appMenuList = appMenuMapper.findAppNavbarMenusByRoleKey(roleKey);
    	if(CollectionUtils.isNotEmpty(appMenuList)){
    		for(AppMenu appMenu : appMenuList){
    			try{
    				AppMenuInfoDTO info1 = new AppMenuInfoDTO();
    				ExtBeanUtils.copyProperties(info1, appMenu);
    				Long menuId = appMenu.getId();
    				
    				//获取对应的2级菜单
    				List<AppMenu> appMenuList2 = appMenuMapper.findAppMenusByRoleKeyAndParentId(roleKey, menuId);
    				List<AppMenuInfoDTO> appMenuInfos2 = new ArrayList<>();
    				if(CollectionUtils.isNotEmpty(appMenuList2)){
    					for(AppMenu appMenu2 : appMenuList2){
    						try{
    							AppMenuInfoDTO info2 = new AppMenuInfoDTO();
    							ExtBeanUtils.copyProperties(info2, appMenu2);
    							appMenuInfos2.add(info2);
    						}catch(Exception e){
    							continue;
    						}
    					}
    				}
    				info1.setChildMenus(appMenuInfos2);
    				appMenuInfos1.add(info1);
    			}catch(Exception e){
    				logger.error(e.getMessage(), e);
    				continue;
    			}
    		}
    	}
    	return appMenuInfos1;
    }
}
